package com.lanvideo.controller;

import com.lanvideo.entity.LearningNote;
import com.lanvideo.service.LearningNoteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 学习笔记控制器
 */
@RestController
@RequestMapping("/api/note")
public class LearningNoteController {

    @Autowired
    private LearningNoteService learningNoteService;

    /**
     * 保存笔记
     */
    @PostMapping("/save")
    public ResponseEntity<Map<String, Object>> saveNote(@RequestBody LearningNote note, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查用户是否已登录
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return ResponseEntity.status(401).body(result);
        }
        
        try {
            // 设置用户ID
            note.setUserId(userId);
            
            // 验证必填字段
            if (note.getVideoId() == null) {
                result.put("success", false);
                result.put("message", "视频ID不能为空");
                return ResponseEntity.ok(result);
            }
            
            if (note.getTitle() == null || note.getTitle().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "笔记标题不能为空");
                return ResponseEntity.ok(result);
            }
            
            if (note.getContent() == null || note.getContent().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "笔记内容不能为空");
                return ResponseEntity.ok(result);
            }
            
            boolean success = learningNoteService.saveNote(note);
            
            if (success) {
                result.put("success", true);
                result.put("message", "笔记保存成功");
            } else {
                result.put("success", false);
                result.put("message", "笔记保存失败");
            }
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "保存笔记失败：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 更新笔记
     */
    @PutMapping("/update")
    public ResponseEntity<Map<String, Object>> updateNote(@RequestBody LearningNote note, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查用户是否已登录
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return ResponseEntity.status(401).body(result);
        }
        
        try {
            // 验证必填字段
            if (note.getId() == null) {
                result.put("success", false);
                result.put("message", "笔记ID不能为空");
                return ResponseEntity.ok(result);
            }
            
            if (note.getTitle() == null || note.getTitle().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "笔记标题不能为空");
                return ResponseEntity.ok(result);
            }
            
            if (note.getContent() == null || note.getContent().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "笔记内容不能为空");
                return ResponseEntity.ok(result);
            }
            
            // 检查笔记是否属于当前用户
            LearningNote existingNote = learningNoteService.getNoteById(note.getId());
            if (existingNote == null || !existingNote.getUserId().equals(userId)) {
                result.put("success", false);
                result.put("message", "笔记不存在或权限不足");
                return ResponseEntity.status(403).body(result);
            }
            
            boolean success = learningNoteService.updateNote(note);
            
            if (success) {
                result.put("success", true);
                result.put("message", "笔记更新成功");
            } else {
                result.put("success", false);
                result.put("message", "笔记更新失败");
            }
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "更新笔记失败：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 删除笔记
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteNote(@PathVariable Integer id, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查用户是否已登录
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return ResponseEntity.status(401).body(result);
        }
        
        try {
            // 检查笔记是否属于当前用户
            LearningNote note = learningNoteService.getNoteById(id);
            if (note == null || !note.getUserId().equals(userId)) {
                result.put("success", false);
                result.put("message", "笔记不存在或权限不足");
                return ResponseEntity.status(403).body(result);
            }
            
            boolean success = learningNoteService.deleteNote(id);
            
            if (success) {
                result.put("success", true);
                result.put("message", "笔记删除成功");
            } else {
                result.put("success", false);
                result.put("message", "笔记删除失败");
            }
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除笔记失败：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 根据ID获取笔记
     */
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getNoteById(@PathVariable Integer id, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查用户是否已登录
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return ResponseEntity.status(401).body(result);
        }
        
        try {
            LearningNote note = learningNoteService.getNoteById(id);
            
            if (note == null) {
                result.put("success", false);
                result.put("message", "笔记不存在");
                return ResponseEntity.ok(result);
            }
            
            // 检查权限：只能查看自己的笔记
            if (!note.getUserId().equals(userId)) {
                result.put("success", false);
                result.put("message", "权限不足");
                return ResponseEntity.status(403).body(result);
            }
            
            result.put("success", true);
            result.put("note", note);
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取笔记失败：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 获取用户的所有笔记
     */
    @GetMapping("/user/{userId}")
    public ResponseEntity<Map<String, Object>> getUserNotes(@PathVariable Integer userId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查用户是否已登录
        Integer currentUserId = (Integer) session.getAttribute("userId");
        Integer userRole = (Integer) session.getAttribute("userRole");
        
        if (currentUserId == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return ResponseEntity.status(401).body(result);
        }
        
        // 检查权限：只能查看自己的笔记，或者管理员可以查看所有笔记
        if (!currentUserId.equals(userId) && (userRole == null || userRole != 0)) {
            result.put("success", false);
            result.put("message", "权限不足");
            return ResponseEntity.status(403).body(result);
        }
        
        try {
            List<LearningNote> notes = learningNoteService.getUserNotes(userId);
            result.put("success", true);
            result.put("notes", notes);
            result.put("count", notes.size());
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取笔记列表失败：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 获取用户对特定视频的笔记
     */
    @GetMapping("/user/{userId}/video/{videoId}")
    public ResponseEntity<Map<String, Object>> getUserVideoNotes(@PathVariable Integer userId, 
                                                               @PathVariable Integer videoId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查用户是否已登录
        Integer currentUserId = (Integer) session.getAttribute("userId");
        Integer userRole = (Integer) session.getAttribute("userRole");
        
        if (currentUserId == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return ResponseEntity.status(401).body(result);
        }
        
        // 检查权限：只能查看自己的笔记，或者管理员可以查看所有笔记
        if (!currentUserId.equals(userId) && (userRole == null || userRole != 0)) {
            result.put("success", false);
            result.put("message", "权限不足");
            return ResponseEntity.status(403).body(result);
        }
        
        try {
            List<LearningNote> notes = learningNoteService.getUserVideoNotes(userId, videoId);
            result.put("success", true);
            result.put("notes", notes);
            result.put("count", notes.size());
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取笔记列表失败：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 搜索笔记
     */
    @GetMapping("/search/{userId}")
    public ResponseEntity<Map<String, Object>> searchNotes(@PathVariable Integer userId, 
                                                         @RequestParam String keyword, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查用户是否已登录
        Integer currentUserId = (Integer) session.getAttribute("userId");
        Integer userRole = (Integer) session.getAttribute("userRole");
        
        if (currentUserId == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return ResponseEntity.status(401).body(result);
        }
        
        // 检查权限：只能搜索自己的笔记，或者管理员可以搜索所有笔记
        if (!currentUserId.equals(userId) && (userRole == null || userRole != 0)) {
            result.put("success", false);
            result.put("message", "权限不足");
            return ResponseEntity.status(403).body(result);
        }
        
        try {
            List<LearningNote> notes = learningNoteService.searchNotes(userId, keyword);
            result.put("success", true);
            result.put("notes", notes);
            result.put("count", notes.size());
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "搜索笔记失败：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }
}
